<?php namespace App\Controllers\Admin;

// =====================================================================
// GALLERY CONTROLLER
// =====================================================================

class GalleryController extends AdminController {
    
    // ---------------------------------------------------------------------        
    // Show,
    // ---------------------------------------------------------------------            
    public function show($id=null) {
        $response['success'] = false;
        if($id) {
            $content_gallery = \ContentsGallery::where('contentID', '=', $id)->first();
            $gallery = \Galleries::find($content_gallery->id);
            if ($gallery != null) {            
                $response['success'] = false;
                $galleryItems = \GalleriesItems::where('galleryID','=',$gallery->id)->get();
                foreach($galleryItems as $key => $item)
                {
                    switch($item['type'])
                    {
                        case 'image':
                            $image =  \Images::find($item->itemID);
                            if ($image != null) {            
                                $response['items'][] = array("type" => $item['type'],
                                                             "to_show" => "<img src='.$image->getUrl().'>");
                            }   
                            break;
                        case 'video':
                            $video =  \Videos::find($item->itemID);
                            if ($video != null) {            
                                $response['items'][] = array('type'         => $item['type'],
                                                             'to_show'      => $video->embed_code);
                            }   
                            break;
                    }
                }
            }
        }
        return \Response::json($response);    
    }
    
    public function getImages($id=null) {
    $response['files'][] = array("file_managerID" => $item->getID(),
                                                 "name" => $item->file_name,
                                                 "url"  => $item->getImageUrl(),
                                                 "size" => 0,
                                                 "thumbnailUrl" => $item->getIconUrl(),
                                                 "deleteUrl" => $GLOBALS['CONF']['url']['root']."/modules/".$module->id."/ajax.php?action=remove_multiple_files&".$obj->_dbIndex."=".$obj->getID()."&file_managerID=".$item->getID(),
                                                 "deleteType" => "delete");
        $response['success'] = false;
        if($id) {
            $content_gallery = \ContentsGallery::where('contentID', '=', $id)->first();
            $gallery = \Galleries::find($content_gallery->id);
            if ($gallery != null) {            
                $response['success'] = false;
                $galleryItems = \GalleriesItems::where('galleryID','=',$gallery->id)->where('type', '=', 'image')->get();
                foreach($galleryItems as $key => $item)
                {
                    $image =  \Images::find($item->itemID);
                    if ($image != null) {            
                        $response['files'][] = array("itemID" => $image->id,
                                                     "name" => $image->name,
                                                     "thumbnailUrl" => $image->getUrl());
                    }   
                }
            }
        }
        return \Response::json($response);    
    }
    
    // ---------------------------------------------------------------------        
    // Store, 
    // ---------------------------------------------------------------------            
    public function store() {

        // Check if gets an object to relate
        $objID = \Input::get('objID');        
        if (!$objID) {
            return \Redirect::back();
        }
        
        // Basic information of an gallery, active, who creates the gallery, etc
        $gallery['active'] = 'Y';
        $gallery['userID_created'] = $this->userID;
        $gallery['userID_modified'] = 0;
        $galleryOBJ = \Galleries::create($gallery);
        
        if($galleryOBJ->id) {
            
            // relate the gallery created with the content
            $contentsGallery['galleryID'] = $galleryOBJ->id;
            $contentsGallery['contentID'] = $objID;
            $contentsGAlleryOBJ = \ContentsGallery::create($contentsGallery);
            
            if($contentsGAlleryOBJ != null) return \Redirect::back()->with('successGallery','gallery has been added successfully.');
        }
        else return \Redirect::back();
    }

    // ---------------------------------------------------------------------        
    // destroy, is the function to delete content.
    // ---------------------------------------------------------------------        
	public function destroy($id=null) {
	        
		try {
	 		$gallery = \Galleries::find($id);
			$delete = $gallery->delete();

		    if ($delete) {
		    
                $contentsGallery = \ContentsGallery::where('galleryID','=',$gallery->id)->first();
                $contentsGallery->delete();		        

		        return \Redirect::back()->with('successGallery', 'Gallery has been deleted successfully.');
		    }
		    else {
		        return \Redirect::back()->with('errorGallery',"Gallery not deleted, please try again");
		    }
		}
		catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
		    return \Redirect::back()->with('errorGallery','Unable to find content');
		}
	}
	
    public function postUploadImage() {
    
        $response['success'] = false;
        $gallerID = \Input::get('galleryID');
	    $items = \Input::file('file');
	    
        foreach($items as $key =>$item) {
           
            $image['active'] = 'Y';
            $image['userID_created'] = $this->userID;
            $image['type']= 'image';
            $image['imageData']= $item;
            $image['userID_modified'] = 0;
            $imageOBJ = \Images::create($image);
            if($imageOBJ != null) {              
            
                $galleryItem['itemID'] = $imageOBJ->id;
                $galleryItem['galleryID'] = $gallerID;
                $galleryItem['type']='image';
                $galleryItem['userID_created'] = $this->userID;
                $galleryItem = \GalleriesItems::create($galleryItem);
                
                $response['items'][] = $imageOBJ->id;
            }
        }
        
        if(count($response['items'])) $response['success'] = true;
    
        return \Redirect::back()->with("response",$response);
    }

    public function postUploadVideo() {
    
        $response['success'] = false;

	    $item = \Input::get();
	    $video['embed_code'] = $item['embed_code'];
        $video['active'] = 'Y';
        $video['userID_created'] = $this->userID;
        $video['userID_modified'] = 0;
        $videoOBJ = \Videos::create($video);
        if($videoOBJ != null) {              
        
            $galleryItem['itemID'] = $videoOBJ->id;
            $galleryItem['galleryID'] = $item['galleryID'];
            $galleryItem['type']=$item['type'];
            $galleryItem['userID_created'] = $this->userID;
            $galleryItem = \GalleriesItems::create($galleryItem);
            
            $response['items'][] = $videoOBJ->id;
        }       
        
        if(count($response['items'])) $response['success'] = true;
    
        return \Redirect::back()->with("response",$response);
    }


    public function postOrderGallery() {   
        $response['success'] = false;
        $newOrderGallery = \Input::get('newOrderItems');
        $newOrder = explode('&',$newOrderGallery); 
        if (is_array($newOrder)) { 
            for($i=0; $i<count($newOrder); $i++) {
                $itemID = intval(str_replace('mySortable[]=', '', $newOrder[$i])); 
                $item = \GalleriesItems::find($itemID); 
                $item->order = $i;
                $noErrors = $item->save();
                if (!$noErrors) break; 
            } 
            
            if ($noErrors) {
                $response['message'] = "List of items ordered successfully."; 
                $response['success'] = true;
            }
            else $response['message'] = "Failed to sort the list of items:". mysql_error(); 
        }    
        
        return \Response::json($response);
    }    
    
    
    
    public function postDeleteItem($id=null)
    {       
        $redirectBack = \Input::get('redirectBack');
        try {
	 		$galleryItem = \GalleriesItems::find($id);
			$delete = $galleryItem->delete();

		    if ($delete) {
		                  
		        return \Redirect::to($redirectBack)->with('successGallery', 'Media Item has been deleted successfully.');
		    }
		    else {
		        return \Redirect::to($redirectBack)->with('errorGallery',"Media Item not deleted, please try again");
		    }
		}
		catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
		    return \Redirect::to($redirectBack)->with('errorGallery','Unable to find content');
		}
    }
}
    
